/// 视频通话准备页面
///
/// 功能：
/// 1. 基于BCP-47标准的语言选择设置（我方语言/对方语言）
/// 2. 通话模式选择（视频通话/语音通话）
/// 3. 使用即构SDK创建真实的视频通话房间
/// 4. 房间创建成功后跳转到视频通话页面
/// 5. 支持通过房间号加入其他人的通话
/// 6. 智能语音自动检测和实时翻译
///
/// 新特性：
/// - 支持41种语言的BCP-47标准代码
/// - 自动检测模式：系统会自动识别双方说话的语言
/// - 实时翻译：无需手动切换，支持双向翻译
/// - 视频/语音通话中禁用TTS，避免干扰通话体验
///
/// 使用说明：
/// - 首次使用需要配置即构SDK的AppID和AppSign
/// - 访问 https://console.zego.im/ 获取配置信息
/// - 在代码中替换 appID 和 appSign 的值

import 'package:flutter/material.dart';
import 'package:zego_express_engine/zego_express_engine.dart';
import 'dart:math' as math;
import '../constants/app_colors.dart';
import '../utils/permission_helper.dart';
import '../services/translation_settings.dart';
import '../components/language_selector.dart';
import 'video_screen.dart';
import 'audio_screen.dart';

import '../app_logger.dart';

// 初始化状态枚举
enum InitializationStatus {
  none,
  requestingPermissions,
  creatingEngine,
  waitingForEngine,
  checkingEngineReady,
  engineReady,
  generatingRoomId,
  completed,
  failed,
}

class VideoChatScreen extends StatefulWidget {
  const VideoChatScreen({Key? key}) : super(key: key);

  // 重置引擎状态的静态方法
  static void resetEngineState() {
    _VideoChatScreenState._isEngineInitialized = false;
    log.d('🔄 引擎状态已重置');
  }

  @override
  State<VideoChatScreen> createState() => _VideoChatScreenState();
}

class _VideoChatScreenState extends State<VideoChatScreen> {
  // 语言选择 - 使用BCP-47标准代码
  String _sourceLanguage = TranslationSettings.instance.fromLanguage; // 从 preferences 读取
  String _targetLanguage = TranslationSettings.instance.toLanguage;   // 从 preferences 读取

  // 通话模式
  bool _isVideoMode = true; // true=视频通话，false=语音通话

  // 创建房间状态
  bool _isCreatingRoom = false;

  // 引擎初始化状态
  static bool _isEngineInitialized = false;

  // 初始化状态跟踪
  InitializationStatus _initStatus = InitializationStatus.none;
  String _initStatusMessage = '';

  // 即构SDK配置 - 请到即构官网获取这些信息
  // 1. 访问 https://console.zego.im/
  // 2. 创建项目获取 AppID 和 AppSign
  static const int appID = 2078585648; // 替换为你的AppID
  static const String appSign = '45e103b5535e74966cb76f929377ae25cd4a0ec3c1ecf6ccffaec4537b2c9e9a'; // 替换为你的AppSign

  @override
  void dispose() {
    // 重置状态
    _initStatus = InitializationStatus.none;
    _initStatusMessage = '';
    _isCreatingRoom = false;

    // 注意：不在这里销毁引擎，因为通话页面还需要使用
    // 引擎的生命周期由通话页面管理

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.background,
      resizeToAvoidBottomInset: true,
      appBar: AppBar(
        title: const Text('音讯视讯通话'),
        backgroundColor: AppColors.cardBackground,
        elevation: 0,
        centerTitle: true,
        titleTextStyle: const TextStyle(
          color: AppColors.textPrimary,
          fontSize: 18,
          fontWeight: FontWeight.w600,
        ),
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(20.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              const SizedBox(height: 20),

              // 语言选择区域
              _buildLanguageSection(),

              const SizedBox(height: 30),

              // 通话模式选择
              _buildCallModeSection(),

              const SizedBox(height: 60),

              // 邀请好友通话按钮
              _buildInviteButton(),

              const SizedBox(height: 20),

              // 通过房间号加入通话
              _buildJoinByRoomId(),

              const SizedBox(height: 40),
            ],
          ),
        ),
      ),
    );
  }

    Widget _buildLanguageSection() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppColors.cardBackground,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.03),
            blurRadius: 6,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Row(
            children: [
              Icon(Icons.language, color: AppColors.primary, size: 20),
              SizedBox(width: 8),
              Text(
                '语言设置',
                style: TextStyle(
                  color: AppColors.textPrimary,
                  fontSize: 14,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),
          // 使用 LanguageSelector 组件
          LanguageSelector(
            sourceLanguage: _sourceLanguage,
            targetLanguage: _targetLanguage,
            onSwap: () {
              setState(() {
                final temp = _sourceLanguage;
                _sourceLanguage = _targetLanguage;
                _targetLanguage = temp;
                log.d('🔄 语言已交换: $_sourceLanguage <-> $_targetLanguage');
              });
              // 同步更新到 preferences
              TranslationSettings.instance.fromLanguage = _sourceLanguage;
              TranslationSettings.instance.toLanguage = _targetLanguage;
            },
            onSourceLanguageChanged: (language) {
              setState(() {
                _sourceLanguage = language;
                log.d('🔄 源语言已改变: $_sourceLanguage');
              });
              // 同步更新到 preferences
              TranslationSettings.instance.fromLanguage = language;
            },
            onTargetLanguageChanged: (language) {
              setState(() {
                _targetLanguage = language;
                log.d('🔄 目标语言已改变: $_targetLanguage');
              });
              // 同步更新到 preferences
              TranslationSettings.instance.toLanguage = language;
            },
            isCompact: false, // 使用常规模式
          ),
        ],
      ),
    );
  }



  Widget _buildCallModeSection() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: AppColors.cardBackground,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.05),
            blurRadius: 10,
            offset: const Offset(0, 5),
          ),
        ],
      ),
      child: Row(
        children: [
          Expanded(
            child: _buildModeOption(
              '视讯通话',
              Icons.videocam,
              _isVideoMode,
              () {
                setState(() {
                  _isVideoMode = true;
                });
              },
            ),
          ),
          const SizedBox(width: 20),
          Expanded(
            child: _buildModeOption(
              '语音通话',
              Icons.call,
              !_isVideoMode,
              () {
                setState(() {
                  _isVideoMode = false;
                });
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildModeOption(String title, IconData icon, bool isSelected, VoidCallback onTap) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.symmetric(vertical: 16),
        decoration: BoxDecoration(
          color: isSelected ? AppColors.primary : AppColors.background,
          borderRadius: BorderRadius.circular(12),
          border: Border.all(
            color: isSelected ? AppColors.primary : Colors.grey.withValues(alpha: 0.3),
          ),
        ),
        child: Column(
          children: [
            Icon(
              icon,
              color: isSelected ? Colors.white : AppColors.textSecondary,
              size: 24,
            ),
            const SizedBox(height: 8),
            Text(
              title,
              style: TextStyle(
                color: isSelected ? Colors.white : AppColors.textSecondary,
                fontSize: 14,
                fontWeight: FontWeight.w500,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildInviteButton() {
    return ElevatedButton(
      onPressed: _isCreatingRoom ? null : _createRoom,
      style: ElevatedButton.styleFrom(
        backgroundColor: _initStatus == InitializationStatus.failed
            ? Colors.red
            : AppColors.primary,
        foregroundColor: Colors.white,
        padding: const EdgeInsets.symmetric(vertical: 16),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(12),
        ),
        elevation: 2,
      ),
      child: _isCreatingRoom
          ? Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    SizedBox(
                      width: 20,
                      height: 20,
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                        valueColor: const AlwaysStoppedAnimation<Color>(Colors.white),
                        value: _getProgressValue(),
                      ),
                    ),
                    const SizedBox(width: 12),
                    Expanded(
                      child: Text(
                        _initStatusMessage.isEmpty ? '加载中...' : _initStatusMessage,
                        style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
                        textAlign: TextAlign.center,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 8),
                Text(
                  _getStatusDescription(),
                  style: const TextStyle(fontSize: 12, color: Colors.white70),
                  textAlign: TextAlign.center,
                ),
                const SizedBox(height: 8),
                TextButton(
                  onPressed: () {
                    setState(() {
                      _isCreatingRoom = false;
                      _initStatus = InitializationStatus.none;
                      _initStatusMessage = '';
                    });
                  },
                  child: const Text(
                    '取消',
                    style: TextStyle(color: Colors.white70, fontSize: 12),
                  ),
                ),
              ],
            )
          : Text(
              _initStatus == InitializationStatus.failed ? '重新尝试' : '邀请好友通话',
              style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
            ),
    );
  }

  // 获取进度值
  double? _getProgressValue() {
    switch (_initStatus) {
      case InitializationStatus.requestingPermissions:
        return 0.1;
      case InitializationStatus.creatingEngine:
        return 0.3;
      case InitializationStatus.waitingForEngine:
        return 0.5;
      case InitializationStatus.checkingEngineReady:
        return 0.7;
      case InitializationStatus.engineReady:
        return 0.9;
      case InitializationStatus.generatingRoomId:
        return 0.95;
      case InitializationStatus.completed:
        return 1.0;
      case InitializationStatus.failed:
        return null;
      default:
        return null;
    }
  }

  // 获取状态描述
  String _getStatusDescription() {
    switch (_initStatus) {
      case InitializationStatus.requestingPermissions:
        return '需要摄像头和麦克风权限';
      case InitializationStatus.creatingEngine:
        return _initStatusMessage.contains('重新初始化')
            ? '正在重新初始化引擎，确保连接稳定...'
            : '正在连接即构服务器...';
      case InitializationStatus.waitingForEngine:
        return '等待服务器响应...';
      case InitializationStatus.checkingEngineReady:
        return '验证连接状态...';
      case InitializationStatus.engineReady:
        return '连接已建立';
      case InitializationStatus.generatingRoomId:
        return '正在创建通话房间...';
      case InitializationStatus.completed:
        return '准备完成，正在进入通话...';
      case InitializationStatus.failed:
        return '点击重新尝试';
      default:
        return '';
    }
  }

  Widget _buildJoinByRoomId() {
    final TextEditingController roomIdController = TextEditingController();

    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppColors.cardBackground,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.grey.withValues(alpha: 0.2)),
      ),
      child: Column(
        children: [
          const Text(
            '通过房间号加入通话',
            style: TextStyle(
              color: AppColors.textSecondary,
              fontSize: 14,
            ),
          ),
          const SizedBox(height: 8),
          Row(
            children: [
              Expanded(
                child: TextField(
                  controller: roomIdController,
                  enabled: !_isCreatingRoom,
                  decoration: InputDecoration(
                    hintText: _isCreatingRoom ? '正在初始化...' : '请输入房间号',
                    border: const OutlineInputBorder(),
                    contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                    fillColor: _isCreatingRoom ? Colors.grey[200] : null,
                    filled: _isCreatingRoom,
                  ),
                  onSubmitted: _isCreatingRoom ? null : (roomId) {
                    _joinRoomById(roomId);
                  },
                ),
              ),
              const SizedBox(width: 8),
              ElevatedButton(
                onPressed: _isCreatingRoom ? null : () {
                  final roomId = roomIdController.text.trim();
                  _joinRoomById(roomId);
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: _isCreatingRoom ? Colors.grey : AppColors.primary,
                  foregroundColor: Colors.white,
                  padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                ),
                child: _isCreatingRoom
                    ? const SizedBox(
                        width: 16,
                        height: 16,
                        child: CircularProgressIndicator(
                          strokeWidth: 2,
                          valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                        ),
                      )
                    : const Text('加入'),
              ),
            ],
          ),
        ],
      ),
    );
  }



        Future<void> _createRoom() async {
    // 重置状态
    setState(() {
      _initStatus = InitializationStatus.none;
      _initStatusMessage = '';
      _isCreatingRoom = true;
      _initStatus = InitializationStatus.requestingPermissions;
      _initStatusMessage = '正在请求权限...';
    });

    // 首先请求视频通话权限
    log.d('🔐 请求视频通话权限...');
    bool hasPermissions = await PermissionHelper.requestVideoCallPermissions(context);

    if (!hasPermissions) {
      log.d('❌ 权限被拒绝，无法启动视频通话');
      setState(() {
        _isCreatingRoom = false;
        _initStatus = InitializationStatus.failed;
        _initStatusMessage = '权限被拒绝';
      });
      return;
    }

    log.d('✅ 权限已授予');

    // 检查SDK配置
    if (appID == 0 || appSign.isEmpty) {
      setState(() {
        _isCreatingRoom = false;
        _initStatus = InitializationStatus.failed;
        _initStatusMessage = '请先配置即构AppID和AppSign';
      });

      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('请先配置即构AppID和AppSign'),
          backgroundColor: Colors.red,
        ),
      );
      return;
    }

    try {
      // 初始化即构SDK（仅做基本初始化，不加入房间）
      await _initializeZegoSDK();

      setState(() {
        _initStatus = InitializationStatus.generatingRoomId;
        _initStatusMessage = '正在生成房间号...';
      });

      // 生成房间ID
      final roomId = _generateRoomId();

      await Future.delayed(const Duration(milliseconds: 500)); // 让用户看到生成房间号的状态

      setState(() {
        _initStatus = InitializationStatus.completed;
        _initStatusMessage = '准备完成';
        _isCreatingRoom = false;
      });

      // 进入视频通话页面，并标记需要显示分享面板
      _joinRoom(roomId, showShareSheet: true);

    } catch (e) {
      setState(() {
        _isCreatingRoom = false;
        _initStatus = InitializationStatus.failed;
        _initStatusMessage = '初始化失败: $e';
      });

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('初始化失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  Future<void> _initializeZegoSDK() async {
    try {
      // 检查引擎是否已经初始化
      if (_isEngineInitialized) {
        setState(() {
          _initStatus = InitializationStatus.creatingEngine;
          _initStatusMessage = '检测到现有引擎，正在重新初始化...';
        });

        log.d('⚠️ 检测到引擎已存在，先销毁现有引擎');

        try {
          // 销毁现有引擎
          ZegoExpressEngine.destroyEngine();
          _isEngineInitialized = false;

          // 等待引擎完全销毁
          await Future.delayed(const Duration(milliseconds: 1000));
          log.d('✅ 现有引擎已销毁');
        } catch (e) {
          log.d('⚠️ 销毁引擎失败: $e，继续创建新引擎');
        }
      }

      setState(() {
        _initStatus = InitializationStatus.creatingEngine;
        _initStatusMessage = '正在创建引擎...';
      });

      log.d('🚀 开始初始化即构SDK引擎...');

      // 创建即构SDK引擎
      await ZegoExpressEngine.createEngineWithProfile(
        ZegoEngineProfile(
          appID,
          ZegoScenario.General,
          appSign: appSign,
        ),
      );

      // 标记引擎已初始化
      _isEngineInitialized = true;

      setState(() {
        _initStatus = InitializationStatus.waitingForEngine;
        _initStatusMessage = '等待引擎就绪...';
      });

      log.d('⏳ 引擎创建完成，等待引擎完全就绪...');

      // 等待引擎完全初始化
      await Future.delayed(const Duration(milliseconds: 1000));

      setState(() {
        _initStatus = InitializationStatus.checkingEngineReady;
        _initStatusMessage = '正在检查引擎状态...';
      });

      // 检查引擎是否创建成功
      bool engineReady = false;
      int retryCount = 0;
      const maxRetries = 10;

      while (!engineReady && retryCount < maxRetries) {
        try {
          final engineState = await ZegoExpressEngine.getVersion();
          if (engineState.isNotEmpty) {
            engineReady = true;
            log.d('✅ 即构SDK引擎初始化成功，版本: $engineState');
          }
        } catch (e) {
          log.d('⏳ 引擎还未完全就绪，等待中... (${retryCount + 1}/$maxRetries)');

          setState(() {
            _initStatusMessage = '检查引擎状态 (${retryCount + 1}/$maxRetries)';
          });
        }

        if (!engineReady) {
          await Future.delayed(const Duration(milliseconds: 500));
          retryCount++;
        }
      }

      if (!engineReady) {
        setState(() {
          _initStatus = InitializationStatus.failed;
          _initStatusMessage = '引擎初始化超时';
        });
        _isEngineInitialized = false;
        throw Exception('引擎初始化超时，请检查网络连接和SDK配置');
      }

      setState(() {
        _initStatus = InitializationStatus.engineReady;
        _initStatusMessage = '引擎就绪完成';
      });

      log.d('🎉 即构SDK引擎完全就绪');

    } catch (e) {
      setState(() {
        _initStatus = InitializationStatus.failed;
        _initStatusMessage = '初始化失败: $e';
      });

      _isEngineInitialized = false;
      log.d('❌ 即构SDK引擎初始化失败: $e');
      rethrow;
    }
  }

  String _generateRoomId() {
    final random = math.Random();
    return (100000 + random.nextInt(900000)).toString();
  }







  void _joinRoom(String roomId, {bool showShareSheet = false}) {
    log.d('🚀 准备加入房间: $roomId');
    log.d('🌐 传递语言设置: $_sourceLanguage -> $_targetLanguage');

    if (_isVideoMode) {
      // 视频通话
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => VideoConversationScreen(
            roomId: roomId,
            showShareSheet: showShareSheet,
            fromLanguage: _sourceLanguage,
            toLanguage: _targetLanguage,
          ),
        ),
      );
    } else {
      // 语音通话
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => AudioConversationScreen(
            roomId: roomId,
            showShareSheet: showShareSheet,
            fromLanguage: _sourceLanguage,
            toLanguage: _targetLanguage,
          ),
        ),
      );
    }
  }

  Future<void> _joinRoomById(String roomId) async {
    if (roomId.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('请输入有效的房间号'),
          backgroundColor: Colors.orange,
        ),
      );
      return;
    }

    // 重置状态
    setState(() {
      _initStatus = InitializationStatus.none;
      _initStatusMessage = '';
      _isCreatingRoom = true;
      _initStatus = InitializationStatus.requestingPermissions;
      _initStatusMessage = '正在请求权限...';
    });

    // 请求权限
    log.d('🔐 请求视频通话权限...');
    bool hasPermissions = await PermissionHelper.requestVideoCallPermissions(context);

    if (!hasPermissions) {
      log.d('❌ 权限被拒绝，无法加入视频通话');
      setState(() {
        _isCreatingRoom = false;
        _initStatus = InitializationStatus.failed;
        _initStatusMessage = '权限被拒绝';
      });
      return;
    }

      log.d('✅ 权限已授予，加入房间: $roomId');

    // 初始化SDK
    try {
      await _initializeZegoSDK();

      setState(() {
        _initStatus = InitializationStatus.completed;
        _initStatusMessage = '准备完成';
        _isCreatingRoom = false;
      });

      _joinRoom(roomId);
    } catch (e) {
      setState(() {
        _isCreatingRoom = false;
        _initStatus = InitializationStatus.failed;
        _initStatusMessage = '初始化失败: $e';
      });

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('初始化失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }
}